<template>
	<view class="order-confirm">
		<base-navbar back-color="#fff" title="确认订单"></base-navbar>
		<!-- <view class="card" v-if="product_type==0"> -->
		<view class="card">
			<uni-segmented-control :values="typeTabs" :current="typeIndex" :active-color="themeColor.theme"
				@clickItem="changeType"></uni-segmented-control>

			<view class="address-card" v-if="typeIndex == 0">
				<view class="icon-map">
					<uni-icons type="location-filled" color="#fff" size="18"></uni-icons>
				</view>
				<view class="info" v-if="addressInfo" @click="pageRoute('/pages/users/address/index')">
					<view class="bd">
						<text class="name">{{addressInfo.consignee}}</text>
						<text class="phone">{{addressInfo.mobile}}</text>
					</view>
					<view class="desc">{{addressInfo.formatAddress}}</view>
				</view>
				<view class="info" v-else @click="pageRoute('/pages/users/address/index')">请选择收货地址</view>
				<uni-icons type="right" color="#909399"></uni-icons>
			</view>

			<view class="site-card" v-else>
				<view class="store-item">
					<image class="thumb" :src="storeInfo.logo" mode="widthFix"></image>
					<view class="info">
						<view class="title">
							<text class="name">{{storeInfo.name}}</text>
							<view class="distance">
								<uni-icons type="location" color="#909399"></uni-icons>
								<text class="label">距{{storeInfo.distance}}km</text>
							</view>
						</view>
						<view class="address">{{storeInfo.formatAddress}}</view>
						<view class="other">
							<text class="time">营业时间 {{storeInfo.business_hours}}</text>
							<text class="sale-num">销量 {{storeInfo.sales_sum}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="card goods-card">
			<view class="goods-item">
				<image class="thumb" mode="widthFix" :src="goodsInfo.logo"></image>
				<view class="info">
					<view class="name">{{goodsInfo.name}}</view>
					<view class="desc">{{goodsInfo.description}}</view>
					<view class="other">
						<goods-price :value="goodsInfo.sale_price">
							<template #suffix>
								<text class="market-price">￥{{goodsInfo.market_price}}</text>
							</template>
						</goods-price>
						<uni-number-box :min="1" :max="10" @change="changeNum"></uni-number-box>
					</view>
				</view>
			</view>

			<view class="cell">
				<view class="cell-item" @click="selectCoupon">
					<text class="name">优惠券</text>
					<view v-if="couponInfo.coupon_name">
						<text class="value">{{couponInfo.coupon_name}}</text>
					</view>
					<view v-else>
						<text class="value" v-if="couponNum==0">无</text>
						<text class="value" v-else>{{couponNum}} 张可用</text>
					</view>
				</view>
				<view class="cell-item">
					<text class="name">订单备注</text>
					<input v-model="orderInfo.user_note" class="value remark" type="text" placeholder="备注" />
				</view>
				<view v-if="typeIndex">
					<view class="cell-item">
						<text class="name"><text style="color: red;">*</text>联系人</text>
						<input v-model="orderInfo.consignee" class="value remark" type="text" placeholder="联系人" />
					</view>
					<view class="cell-item">
						<text class="name"><text style="color: red;">*</text>联系电话</text>
						<input v-model="orderInfo.mobile" class="value remark" type="text" placeholder="联系电话" />
					</view>
					<view class="cell-item">
						<text>请填写联系人和联系电话，方便门店客服与您联系！</text>
					</view>
				</view>
			</view>

			<view class="tool-bar">
				<view class="inner">
					<view class="sum">
						<text class="label">总计支付:</text>
						<text class="value">￥{{orderInfo.pay_amount}}</text>
					</view>
					<c-button type="warning" round @click="submit">提交订单</c-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import checkLogin from '@/utils/login';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject
	} from 'vue';
	import {
		onLoad,
		onShow,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const state = reactive({
		themeColor: JSON.parse(cache.get('themeColor')),
		product_type: 0,
		goodsInfo: {},
		addressInfo: [],
		storeInfo: [],
		couponNum: 0,
		couponInfo: {
			couponTypeInfo: {
				money: 0,
			}
		},
		typeTabs: ['物流配送', '到店自提'],
		typeIndex: 0,
		orderInfo: {
			price: 0,
			num: 1,
			total_amount: 0,
			pay_amount: 0,
			discount_money: 0,
			address_id: 0,
			store_id: 0,
			coupon_id: 0,
			consignee: '',
			mobile: '',
			receiving_method: 0,
			user_note: '',
		},
	});

	onLoad((opt) => {
		if (opt.hasOwnProperty('goods_id')) {
			state.goodsInfo.id = opt.goods_id;
			getGoodsDetail();
		}
		//选择地址
		uni.$on('select_address', (res) => {
			// console.log('选择地址', res.address_info);
			state.addressInfo = res.address_info;
			state.orderInfo.address_id = res.address_info.id;
		})
		//选择门店
		uni.$on('select_store', (res) => {
			// console.log('选择门店', res.store_info);
			state.storeInfo = res.store_info;
			state.orderInfo.store_id = res.store_info.id;
			getContactInfo();
		})
		//选择优惠券
		uni.$on('select_coupon', (res) => {
			console.log('选择优惠券', res.coupon_info);
			state.couponInfo = res.coupon_info;
			state.orderInfo.coupon_id = res.coupon_info.id;
			//计算使用优惠券后的价格
			calculatePrice();
		})
		getAddress();
		getAvailableCouponsNum();
	});

	onShow(() => {});

	onPullDownRefresh((e) => {
		console.log("下拉刷新", e);
	});

	onReachBottom((e) => {
		console.log("上拉加载更多", e);
	});

	function getGoodsDetail() {
		request.get('goods/info', {
			id: state.goodsInfo.id
		}).then(res => {
			console.log('商品详情', res);
			state.goodsInfo = res.data;
			state.product_type = res.data.product_type;
			state.orderInfo.goods_id = res.data.id;
			state.orderInfo.store_id = res.data.store_id;
			state.orderInfo.price = res.data.sale_price;
			calculatePrice();
			getStoreInfo();
		})
	}

	function getStoreInfo() {
		request.get('store/info', {
			id: state.goodsInfo.store_id,
			longitude: cache.get('longitude'),
			latitude: cache.get('latitude'),
		}).then(res => {
			console.log('店铺详情', res);
			state.storeInfo = res.data;
		})
	}

	function getAddress() {
		request.get('address/getAddress').then(res => {
			state.addressInfo = res.data;
			state.orderInfo.address_id = res.data.id;
			state.orderInfo.consignee = res.data.consignee;
			state.orderInfo.mobile = res.data.mobile;
		})
	}

	function getAvailableCouponsNum() {
		request.get('coupon/getAvailableCouponsNum').then(res => {
			console.log('可用优惠券', res);
			state.couponNum = res.data;
		})
	}

	function selectCoupon() {
		pageRoute('/pages/marketing/coupon/coupon?operate=select&store_id=' + state.orderInfo.store_id + '&goods_id=' +
			state.orderInfo.goods_id + '&price=' + state.orderInfo.pay_amount);
	}

	function changeNum(val) {
		state.orderInfo.num = val;
		calculatePrice();
	}

	function submit() {
		//登录过期自动登录
		if (!checkLogin()) {
			uni.showModal({
				title: '提示',
				content: '请先授权登录',
				success: function(res) {
					uni.reLaunch({
						url: "/pages/users/login/login"
					})
				}
			});
		} else {
			if (state.typeIndex) {
				//到店自提
				if (state.storeInfo.length == 0) {
					uni.showToast({
						title: '请选择门店'
					})
					return;
				}
				if (!state.orderInfo.consignee) {
					uni.showToast({
						title: '请填写联系人'
					})
					return;
				}
				if (!state.orderInfo.mobile) {
					uni.showToast({
						title: '请填写联系电话'
					})
					return;
				}
			} else {
				//物流配送
				if (state.addressInfo.length == 0) {
					uni.showToast({
						title: '请选择地址'
					})
					return;
				}
			}

			if (state.product_type) {
				state.orderInfo.receiving_method = -1;
			} else {
				state.orderInfo.receiving_method = state.typeIndex;
			}
			console.log('提交订单', state.orderInfo);
			request.post('order/create', state.orderInfo).then(res => {
				console.log(res);
				uni.showToast({
					title: res.msg,
					duration: 2000
				})
				if (res.code === 1) {
					if (res.data.pay_type === '1') {
						//官方支付
						pageRoute('/pages/order/pay/pay?trade_no=' + res.data.trade_no);
					} else if (res.data.pay_type === '2') {
						//星驿付支付
						pageRoute('/pages/order/pay/xyfpay?trade_no=' + res.data.trade_no);
					} else if (res.data.pay_type === '3') {
						//汇付支付
						pageRoute('/pages/order/pay/hfpay?trade_no=' + res.data.trade_no);
					}
				}
			})
		}
	}

	function calculatePrice() {
		state.orderInfo.total_amount = state.orderInfo.price * state.orderInfo.num;
		state.orderInfo.pay_amount = state.orderInfo.total_amount;
		//重新计算优惠后金额
		if (state.couponInfo && state.couponInfo.couponTypeInfo.money) {
			state.orderInfo.pay_amount -= state.couponInfo.couponTypeInfo.money;
			state.orderInfo.discount_money = state.couponInfo.couponTypeInfo.money;
		}
	}

	function changeType(e) {
		const index = e.currentIndex;
		state.typeIndex = index;
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	};

	function pageTabRoute(url) {
		uni.switchTab({
			url
		});
	};

	const {
		themeColor,
		product_type,
		goodsInfo,
		addressInfo,
		storeInfo,
		couponNum,
		couponInfo,
		typeTabs,
		typeIndex,
		orderInfo,
	} = toRefs(state);
</script>

<style lang="scss">
	page {
		background-color: $bg-color;
	}

	.order-confirm {
		padding: $margin-24 $margin-24 calc(env(safe-area-inset-bottom) + 100rpx);

		.card {
			margin-bottom: $margin-24;
			background-color: $bg-inverse-color;
			border-radius: $radius-12;
		}

		.site-card {
			padding: $margin-24;

			.store-item {
				@include f-between;
				padding: $margin-24 0;
				border-bottom: 2rpx solid mix($white-color, $border-color, 40%);

				&:last-child {
					border-bottom: none;
				}

				.thumb {
					width: 128rpx;
					height: 128rpx;
					background-color: $bg-color;
					border-radius: $radius-8;
				}

				.info {
					flex: 1;
					margin-left: $margin-24;

					.title {
						@include f-between;

						.name {
							@include ellipsis;
							flex: 1;
							font-size: $font-30;
							color: $main-color;
							font-weight: 500;
						}

						.distance {
							@include f-center;
							font-size: $font-22;
							color: $tips-color;
						}
					}

					.address {
						@include ellipsis;
						margin-top: $margin-8;
						font-size: $font-24;
						color: $tips-color;
					}

					.other {
						@include f-between;
						margin-top: $margin-20;

						.time,
						.sale-num {
							font-size: $font-24;
							color: $tips-color;
						}
					}
				}
			}

			.info {
				.top {
					@include f-between;

					.name {
						@include ellipsis;
						color: $main-color;
						font-size: $font-32;
						font-weight: bold;
					}

					.more {
						@include f-center;

						.label {
							font-size: $font-24;
							color: $success-color;
						}
					}
				}

				.address {
					@include f-between;
					margin-top: $margin-12;

					.value {
						font-size: $font-24;
						color: $tips-color;
					}

					.label {
						font-size: $font-24;
						color: $warning-color;
					}
				}
			}

			.other {
				@include f-between;
				margin-top: $margin-20;

				.time,
				.phone {
					display: flex;
					flex-direction: column;

					.label {
						font-size: $font-24;
						color: $tips-color;
					}

					.value {
						color: $main-color;
						font-weight: 500;
					}
				}
			}
		}

		.address-card {
			@include f-between;
			padding: $margin-24;

			.icon-map {
				@include f-center;
				width: 36rpx;
				height: 36rpx;
				background-color: $success-color;
				border-radius: $radius-circle;
			}

			.info {
				flex: 1;
				margin-left: $margin-16;

				.name {
					color: $main-color;
					font-weight: bold;
				}

				.desc,
				.phone {
					font-size: $font-24;
					color: $tips-color;
				}

				.phone {
					margin-left: $margin-12;
				}

				.desc {
					margin-top: $margin-8;
				}
			}
		}

		.goods-card {
			padding: 0 $margin-24;

			.store {
				padding: $margin-24 0;
				display: flex;
				align-items: center;

				.name {
					color: $main-color;
				}
			}

			.goods-item {
				@include f-between;
				padding: $margin-16 0;

				.thumb {
					width: 128rpx;
					height: 128rpx;
					background-color: $bg-color;
					border-radius: $radius-8;
				}

				.info {
					flex: 1;
					margin-left: $margin-24;

					.name {
						color: $main-color;
						font-weight: 500;
					}

					.desc {
						margin-top: $margin-8;
						font-size: $font-24;
						color: $tips-color;
					}
				}

				.other {
					@include f-between;
					margin-top: $margin-20;

					.market-price {
						text-decoration: line-through;
						font-size: $font-24;
						color: $tips-color;
					}
				}
			}

			.cell {
				.cell-item {
					@include f-between;
					padding: $margin-24 0;
					border-bottom: 1rpx solid mix($inverse-color, $border-color, 35%);

					&:last-child {
						border-bottom: none;
					}

					.name {
						color: $tips-color;
					}

					.value {
						color: $main-color;
						font-weight: 500;

						&.remark {
							text-align: right;
						}
					}
				}
			}
		}

		.tool-bar {
			position: fixed;
			bottom: 0;
			left: 0;
			z-index: 99;
			width: 100%;
			background-color: $bg-inverse-color;
			padding-bottom: env(safe-area-inset-bottom);
			box-sizing: 0 -1rpx 6rpx rgba(0, 0, 0, 0.1);

			.inner {
				@include f-between;
				height: 100rpx;
				padding: 0 $margin-24;

				.sum {
					.value {
						font-size: $font-32;
						font-weight: bold;
						color: $error-color;
					}
				}
			}
		}
	}
</style>